package cn.wk.service.impl;

import cn.wk.domain.LoginUser;
import cn.wk.mapper.LoginUserMapper;
import cn.wk.properties.ClientDetailAdminProperties;
import cn.wk.properties.ClientDetailWebsiteProperties;
import cn.wk.service.ILoginUserService;
import cn.wk.util.AjaxResult;
import cn.wk.util.HttpUtil;
import cn.wk.utils.ValidUtils;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wk
 * @since 2021-03-05
 */
@Service
public class LoginUserServiceImpl extends ServiceImpl<LoginUserMapper, LoginUser> implements ILoginUserService {
    @Value("${auth.password.tokenurl}")
    private String tokenUrl;
    @Autowired
    private ClientDetailWebsiteProperties websiteProperties;
    @Autowired
    private ClientDetailAdminProperties adminProperties;
    @Autowired
    private LoginUserMapper loginUserMapper;

    @Override
    public boolean insert(LoginUser login) {
        //保存t_login_user表，得到其主键id
        super.insert(login);
        //再保存t_user_meal表
        loginUserMapper.saveUserMeal(login.getId(), login.getMealId());
        return true;
    }

    /**
     * 登录
     *
     * @param loginUser
     * @return
     */
    @Override
    public AjaxResult login(LoginUser loginUser) {
        String username = loginUser.getUsername();
        String password = loginUser.getPassword();
        Integer type = loginUser.getType();
        ValidUtils.assertNotNull(username, "用户名不能为空");
        ValidUtils.assertNotNull(password, "密码不能为空");
        ValidUtils.assertNotNull(type, "参数错误，请刷新");
        //定义oauth类型
        String clientId = null;
        //定义密码
        String secret = null;
        if (type.intValue() == LoginUser.TYPE_ADMIN) {    //type为0就是后台
            clientId = adminProperties.getClientid();
            secret = adminProperties.getSecret();
            System.out.println("------type为0就是后台-------------");
        } else {
            clientId = websiteProperties.getClientid();
            secret = websiteProperties.getSecret();
            System.out.println(clientId);
            System.out.println(secret);
            System.out.println("------type为1-------------");
        }
        String url = String.format(tokenUrl, clientId, secret, username, password);
        System.out.println(url);
        //发送http请求
        Map<String, String> map = HttpUtil.sendPost(url);
        System.out.println(map);
        boolean success = true;
        String error = null;
        if (null == map.get("access_token")) {
            success = false;
            error = map.get("error_description");
        }

        //4.返回Token
        return AjaxResult.me().setSuccess(success).setResultObj(map).setMessage(error);
    }
}
